<template>
  <a-collapse-panel  name="element-form-field">
    <template #header>
      <collapse-title title="表单字段">
        <lucide-icon name="FileCog" />
      </collapse-title>
      <number-tag :value="formFields.length" margin-left="12px" />
    </template>
    <div>
      <a-table border size="small" :data-source="formFields" style="width: 100%" height="200px">
        <a-table-column title="序号" type="index" data-index="index" width="50">
          <template v-slot:default="text, record, index">
            <span>{{ index + 1 }}</span>
          </template>
        </a-table-column>
        <a-table-column title="编号" key="id" data-index="id" show-overflow-tooltip />
        <a-table-column title="名称" key="label" data-index="label" show-overflow-tooltip />
        <a-table-column title="类型" show-overflow-tooltip>
          <template v-slot:default="scope">
            <span>{{ getType(scope.row.type) }}</span>
          </template>
        </a-table-column>
        <a-table-column
          title="默认值"
          key="defaultValue"
          data-index="defaultValue"
          show-overflow-tooltip
        />
        <a-table-column title="操作" width="80" fixed="right">
          <template v-slot:default="text, record, index">
            <a-button type="link" @click="removeProperty(index)">移除</a-button>
          </template>
        </a-table-column>
      </a-table>

      <a-button style="margin-top: 5px" type="primary" block @click="openModel(-1)">
        添加表单字段
      </a-button>
    </div>
    <a-drawer
      v-model:visible.sync="modelVisible"
      title="添加表单字段"
      width="480px"
      append-to-body
      destroy-on-close
      :bodyStyle="{ height: 'calc(100vh - 120px)', overflow: 'auto' }"
      @close="() => (modelVisible = false)"
    >
      <a-form-model
        ref="formRef"
        :model="formFieldForm"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        size="small"
        @submit.native.prevent
      >
        <a-form-item label="编号">
          <a-input v-model="formFieldForm.id" clearable @keydown.enter.prevent />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-model="formFieldForm.label" clearable @keydown.enter.prevent />
        </a-form-item>
        <a-form-item label="类型">
          <a-select
            v-model="formFieldForm.type"
            placeholder="请选择类型"
            clearable
            style="width: 100%"
          >
            <a-select-option v-for="(item, key) of fieldType" :value="item.value" :key="key">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="默认值">
          <a-input v-model="formFieldForm.defaultValue" clearable />
        </a-form-item>
      </a-form-model>
      <!-- 校验规则 -->
      <a-divider key="validation-divider" />
      <p class="listener-filed__title" key="validation-title">
        <span><i class="a-icon-menu"></i>约束条件列表：</span>
        <a-button size="small" type="primary" @click="showConstraintsModal()">添加约束</a-button>
      </p>
      <a-table
        :data="fieldConstraintsList"
        size="small"
        key="validation-table"
        max-height="240"
        border
        fit
      >
        <a-table-column title="序号" width="50px" type="index" />
        <a-table-column title="约束名称" key="name" min-width="100px" show-overflow-tooltip />
        <a-table-column title="约束配置" key="config" min-width="100px" show-overflow-tooltip />
        <a-table-column title="操作" width="90px">
          <template v-slot:default="{ $index }">
            <a-button size="small" type="text" @click="showConstraintsModal($index)">编辑</a-button>
            <a-divider direction="vertical" />
            <a-button
              size="small"
              type="text"
              style="color: #ff4d4f"
              @click="removeConstraints($index)"
            >
              移除
            </a-button>
          </template>
        </a-table-column>
      </a-table>

      <!-- 表单属性 -->
      <a-divider key="property-divider" />
      <p class="listener-filed__title" key="property-title">
        <span><i class="a-icon-menu"></i>字段属性列表：</span>
        <a-button size="small" type="primary" @click="showPropertiesModal()">添加属性</a-button>
      </p>
      <a-table
        :data="fieldPropertiesList"
        size="small"
        key="property-table"
        max-height="240"
        border
        fit
      >
        <a-table-column title="序号" width="50px" type="index" />
        <a-table-column title="属性编号" key="id" min-width="100px" show-overflow-tooltip />
        <a-table-column title="属性值" key="value" min-width="100px" show-overflow-tooltip />
        <a-table-column title="操作" width="90px">
          <template v-slot:default="{ $index }">
            <a-button size="small" type="text" @click="showPropertiesModal($index)">编辑</a-button>
            <a-divider direction="vertical" />
            <a-button
              size="small"
              type="text"
              style="color: #ff4d4f"
              @click="removeProperties($index)"
              >移除</a-button
            >
          </template>
        </a-table-column>
      </a-table>
      <div class="drawer-bootom-button">
        <a-button @click="modelVisible = false">取 消</a-button>
        <a-button type="primary" @click="addFormField">确 认</a-button>
      </div>
    </a-drawer>
    <a-modal
      v-model:visible.sync="constraintsModelVisible"
      title="添加约束条件"
      width="640px"
      append-to-body
      destroy-on-close
    >
      <a-form-model ref="formRef" :model="newConstraints" :rules="rules" aria-modal="true">
        <a-form-item path="name" label="约束名称(name)">
          <a-input v-model="newConstraints.name" @keydown.enter.prevent />
        </a-form-item>
        <a-form-item path="config" label="约束配置(config)">
          <a-input v-model="newConstraints.config" @keydown.enter.prevent />
        </a-form-item>
      </a-form-model>
      <template #footer>
        <a-button @click="constraintsModelVisible = false">取 消</a-button>
        <a-button type="primary" @click="addConstraints">确 认</a-button>
      </template>
    </a-modal>
    <a-modal
      v-model:visible.sync="propertiesModelVisible"
      title="添加字段属性"
      width="640px"
      append-to-body
      destroy-on-close
    >
      <a-form-model ref="formRef" :model="newProperties" :rules="rules" aria-modal="true">
        <a-form-model-item label="属性编号(id)">
          <a-input v-model="newProperties.id" @keydown.enter.prevent />
        </a-form-model-item>
        <a-form-model-item label="属性值( Value )">
          <a-input v-model="newProperties.value" @keydown.enter.prevent />
        </a-form-model-item>
      </a-form-model>
      <template #footer>
        <a-button @click="propertiesModelVisible = false">取 消</a-button>
        <a-button type="primary" @click="addProperties">确 认</a-button>
      </template>
    </a-modal>
  </a-collapse-panel>
</template>

<script>
import {
  addFormFieid,
  getFormField,
  removeFormFieid
} from "@/bo-utils/FormFieldUtil";
import EventEmitter from '@/utils/EventEmitter'
import { getBusinessObject } from "bpmn-js/lib/util/ModelUtil";
import { mapState } from 'pinia'
import modelerStore from '@/store/modeler'
export default {
  name: "ElementFormField",
  title: "表单字段",
  icon: "file-excel",
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      formFields: [],
      formFieldForm: {
        id: "",
        label: "",
        type: "",
        defaultValue: ""
      },
      fieldConstraintsList: [],
      fieldPropertiesList: [],
      fieldType: [
        { label: "布尔", value: "boolean" },
        { label: "日期", value: "date" },
        { label: "枚举", value: "enum" },
        { label: "长整形", value: "long" },
        { label: "字符串", value: "string" },
        { label: "自定义类型", value: "custom" }
      ],
      rules: {
        name: {
          required: true,
          message: "属性名称不能为空",
          trigger: ["blur", "change"]
        },
        value: {
          required: true,
          message: "属性值不能为空",
          trigger: ["blur", "change"]
        }
      },
      modelVisible: false,
      formHandlerClass: "",
      constraintsModelVisible: false,
      newConstraints: {
        name: "",
        config: ""
      },
      currentConstraintsIndex: "",
      propertiesModelVisible: false,
      newProperties: {
        id: "",
        value: ""
      },
      currentPropertiesIndex: ""
    };
  },
  mounted() {
    this.reloadFormFieid();
    EventEmitter.on("element-update", this.reloadFormFieid);
    this.init();
  },
  methods: {
    init() {
      const element = this.getActive;
      const businessObject = getBusinessObject(element);
      this.formHandlerClass = businessObject.get("formHandlerClass");
    },
    async reloadFormFieid() {
      this.modelVisible = false;
      await this.$nextTick();
      this.newProperty = { id: "", label: "", type: "", defaultValue: "" };
      this._formFieldsRaw = getFormField(this.getActive);
      this.formFields = JSON.parse(JSON.stringify(this._formFieldsRaw));
    },
    removeProperty(propIndex) {
      removeFormFieid(this.getActive, this._formFieldsRaw[propIndex]);
      this.reloadFormFieid();
    },
    async addFormField() {
      await this.$refs.formRef.validate();
      const formFieldForm = {
        ...this.formFieldForm
      };
      addFormFieid(
        this.getActive,
        formFieldForm,
        this.fieldPropertiesList,
        this.fieldConstraintsList
      );
      await this.reloadFormFieid();
    },
    async openModel() {
      this.modelVisible = true;
      await this.$nextTick();
      this.$refs.formRef.clearValidate();
    },
    getType(type) {
      if (!type) {
        return "";
      }
      return this.fieldType.filter(item => item.value === type)[0].label;
    },
    showConstraintsModal(index) {
      this.currentConstraintsIndex = index;
      if (index !== undefined) {
        this.newConstraints = {
          ...this.fieldConstraintsList[index]
        };
      } else {
        this.newConstraints = {
          name: "",
          config: ""
        };
      }
      this.constraintsModelVisible = true;
    },
    removeConstraints(index) {
      this.fieldConstraintsList.splice(index, 1);
    },
    addConstraints() {
      if (this.currentConstraintsIndex === undefined) {
        this.fieldConstraintsList.push(this.newConstraints);
      } else {
        this.fieldConstraintsList.splice(
          this.currentConstraintsIndex,
          1,
          this.newConstraints
        );
      }

      this.constraintsModelVisible = false;
    },
    showPropertiesModal(index) {
      this.currentPropertiesIndex = index;
      if (index !== undefined) {
        this.newProperties = {
          ...this.fieldPropertiesList[index]
        };
      } else {
        this.newProperties = {
          id: "",
          value: ""
        };
      }
      this.propertiesModelVisible = true;
    },
    removeProperties(index) {
      this.fieldPropertiesList.splice(index, 1);
    },
    addProperties() {
      if (this.currentPropertiesIndex === undefined) {
        this.fieldPropertiesList.push(this.newProperties);
      } else {
        this.fieldPropertiesList.splice(
          this.currentPropertiesIndex,
          1,
          this.newProperties
        );
      }
      this.propertiesModelVisible = false;
    }
  },
  computed: {
    ...mapState(modelerStore, ['getActive', 'getActiveId']),
  }
};
</script>
<style scoped>
.element-drawer__button {
  margin-top: 8px;
  width: 100%;
  display: inline-flex;
  justify-content: space-around;
}
.element-drawer__button > .a-button {
  width: 100%;
}
.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
  z-index: 99;
}
.drawer-bootom-button .ant-btn {
  margin-right: 10px;
}
</style>
